using Application.Core.Entity;


namespace Application.Service.LogCache;

/// <summary>
/// 系统日志服务实现
/// </summary>
[ApiDescriptionSettings(SplitCamelCase = false)]
[Route("api/log")]
public class SystemLogService : IDynamicApiController, IScoped
{
    private readonly ISqlSugarClient _db;

    public SystemLogService(ISqlSugarClient db)
    {
        _db = db;
    }

    /// <summary>
    /// 获取日志级别列表
    /// </summary>
    /// <returns>级别列表</returns>
    [HttpGet("Level")]
    public string[] GetLogLevels()
    {
        return new string[]
        {
                "Trace" ,
                "Debug" ,
                "Information" ,
                "Warning" ,
                "Error" ,
                "Critical"
        };
    }


    /// <summary>
    /// 查询系统日志
    /// </summary>
    /// <returns>日志列表</returns>
    [SwaggerIgnore]
    public async Task<IEnumerable<SystemLog>> GetAllEntiyAsync()
    {
        var dbCopy = _db.CopyNew();
        try
        {
            var logs = await dbCopy.Queryable<SystemLog>().OrderBy(u => u.Id).ToListAsync();
            return logs;
        }
        catch (Exception ex)
        {
            Log.Error($"获取所有日志失败!", ex);
            throw Oops.Bah($"获取所有日志失败!", ex);
        }
        finally
        {
            dbCopy.Close();
            dbCopy.Dispose();
        }
    }

    /// <summary>
    /// 添加系统日志
    /// </summary>
    [SwaggerIgnore]
    
    public async Task<bool> AddLogAsync(SystemLog log)
    {
        var dbNew = _db.CopyNew();
        try
        {
            await dbNew.Insertable(log).ExecuteCommandAsync();
            return true;
        }
        catch
        {
            return false;
        }
        finally
        {
            dbNew.Close();
            dbNew.Dispose();
        }
    }

    /// <summary>
    /// 查询系统日志(分页)
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>日志列表</returns>
    [HttpGet("Page")]
    public async Task<dynamic> QueryLogsPageAsync(LogQueryDto request)
    {
        var logs = await QueryLogsAsync(request);
        var totalCount = await GetLogCountAsync(request);

        return new
        {
            Success = true,
            Data = logs,
            TotalCount = totalCount,
            PageIndex = request.PageIndex,
            PageSize = request.PageSize,
            TotalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize)
        };
    }

    /// <summary>
    /// 查询系统日志
    /// </summary>
    [HttpGet("Info")]
    public async Task<IEnumerable<SystemLog>> QueryLogsAsync(LogQueryDto request)
    {
        var query = BuildQuery(request);

        // 应用排序
        query = ApplySorting(query, request);

        // 应用分页
        var pageList = await query.ToPageListAsync(request.PageIndex, request.PageSize);
        return pageList;
    }

    /// <summary>
    /// 获取日志数量
    /// </summary>
    [HttpGet("Count")]
    public async Task<int> GetLogCountAsync(LogQueryDto request)
    {
        var query = BuildQuery(request);
        return await query.CountAsync();
    }

    /// <summary>
    /// 清空日志
    /// </summary>
    [SwaggerIgnore]
    public async Task<dynamic> ClearLogsAsync()
    {
        var dbNew = _db.CopyNew();
        try
        {
            await dbNew.Deleteable<SystemLog>().ExecuteCommandAsync();
            return new
            {
                Success = true,
                Message = "日志清空成功"
            };
        }
        catch
        {
            return new
            {
                Success = false,
                Message = "日志清空失败"
            };
        }
        finally
        {
            dbNew.Close();
            dbNew.Dispose();
        }
    }

    /// <summary>
    /// 构建查询条件
    /// </summary>
    private ISugarQueryable<SystemLog> BuildQuery(LogQueryDto request)
    {
        var dbNew = _db.CopyNew();
        try
        {
            var query = dbNew.Queryable<SystemLog>();

            // 搜索关键词
            if (!string.IsNullOrEmpty(request.SearchText))
            {
                query = query.Where(x =>
                    x.Message.Contains(request.SearchText) ||
                    x.Exception.Contains(request.SearchText) ||
                    x.CallerMemberName.Contains(request.SearchText) ||
                    x.CallerFilePath.Contains(request.SearchText) ||
                    x.UserName.Contains(request.SearchText) ||
                    x.Module.Contains(request.SearchText)
                );
            }

            // 日志级别筛选
            if (!string.IsNullOrEmpty(request.Level))
            {
                query = query.Where(x => x.Level == request.Level);
            }

            // 时间范围筛选
            if (request.StartTime.HasValue)
            {
                query = query.Where(x => x.CreateTime >= request.StartTime.Value);
            }

            if (request.EndTime.HasValue)
            {
                query = query.Where(x => x.CreateTime <= request.EndTime.Value);
            }

            return query;
        }
        catch
        {
            return _db.Queryable<SystemLog>();
        }
        finally
        {
            dbNew.Close();
            dbNew.Dispose();
        }
    }

    /// <summary>
    /// 应用排序
    /// </summary>
    private ISugarQueryable<SystemLog> ApplySorting(ISugarQueryable<SystemLog> query, LogQueryDto request)
    {
        if (string.IsNullOrEmpty(request.SortField))
        {
            return query.OrderBy(x => x.CreateTime, OrderByType.Desc);
        }

        var sortDirection = request.SortDirection?.ToLower() == "asc" ? OrderByType.Asc : OrderByType.Desc;

        return request.SortField.ToLower() switch
        {
            "id" => query.OrderBy(x => x.Id, sortDirection),
            "level" => query.OrderBy(x => x.Level, sortDirection),
            "createtime" => query.OrderBy(x => x.CreateTime, sortDirection),
            "username" => query.OrderBy(x => x.UserName, sortDirection),
            "module" => query.OrderBy(x => x.Module, sortDirection),
            _ => query.OrderBy(x => x.CreateTime, OrderByType.Desc)
        };
    }
}
